package com.xbongbong.paas.script.help;

import com.alibaba.fastjson.JSON;
import com.xbongbong.paas.redis.PaasRedisHelper;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.sys.enums.JobStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 统一异常处理
 * @author kaka
 * @time 2018-9-18 14:46
 */
@ControllerAdvice
public class JobExceptionHandle {

    private static final Logger LOG = LoggerFactory.getLogger(JobExceptionHandle.class);

    @Resource
    private PaasRedisHelper paasRedisHelper;

    private static String filePrefix = "autoJob";

    private static String prdEsName = "prd_";

    private static String jobApplication = "pro-web-script";

    @Value("${spring.application.name}")
    private String application;

    @Value("${com.xbongbong.pro.main.esname}")
    private String esName;




    /**
     * 将controller层出现的异常捕获，记录error日志
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public String exceptionHandle(HttpServletRequest request, Exception e) {
        XbbResponse response;
        if (e instanceof XbbException) {
            response = new XbbResponse((XbbException)e);
        } else if (e instanceof HttpRequestMethodNotSupportedException) {
            response = new XbbResponse(new XbbException(SystemErrorCodeEnum.API_ERROR_100002, I18nStringConstant.ONLY_SUPPORTS_POST_REQUESTS));
        } else if (e instanceof HttpMessageNotReadableException) {
            response = new XbbResponse(new XbbException(SystemErrorCodeEnum.API_ERROR_100064));
        } else {
            response = new XbbResponse(new XbbException(SystemErrorCodeEnum.API_ERROR_100063));
        }
        LOG.error("ExceptionHandle.exceptionHandle 截获异常 : ", e);
        jobShutDown(request.getRequestURI());

        return JSON.toJSONString(response);
    }

    private void jobShutDown(String url) {
        if (!Objects.equals(prdEsName,esName) && Objects.equals(jobApplication,application)) {
            Long ttl = paasRedisHelper.getExpire(filePrefix,url);
            if (ttl > 0) {
                paasRedisHelper.setValue(filePrefix,url, JobStatusEnum.ERROR.getCode(),ttl.intValue());
            }
        }
    }
}
